package com.hmdp.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author 安贺
 * @createTime 2022年08月30日 12:37:00
 * @description
 */
@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }
    public String get(String key){
       return stringRedisTemplate.opsForValue().get(key);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        //设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R, ID> R queryWithPassThrough(String keyPrefix , ID id, Class<R> type,
                                          Function<ID,R> dbFallback,Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查询数据库
        String jsonStr = this.get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(jsonStr)) {
            //3.存在直接返回
            return JSONUtil.toBean(jsonStr, type);
        }
        //判断是否命中空值
        if (jsonStr != null) {
            return null;
        }

        //4.不存在查询数据库
        R r = dbFallback.apply(id);
        if (ObjectUtil.isEmpty(r)) {
            this.set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //库里存在，redis缓存
        this.set(key,r,time,unit);

        return r;
    }

    /**
     * 互斥锁，加锁
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //转为基本类型，直接返回的话拆箱过程中可能空指针
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 互斥锁，释放锁
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);

    /**
     * 缓存击穿解决方案，逻辑过期
     *
     * @param id
     * @return
     */
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,Class<R> type,
                                           Function<ID,R> dbFallback,Long time, TimeUnit unit,String lockKeyPrefix) {
        //1.从redis中查询数据库
        String key = keyPrefix+id;
        String json = this.get(key);
        //2.判断是否命中
        if (StrUtil.isBlank(json)) {
            //3.不命中直接返回空
            return null;
        }
        //4.命中，需要先反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1 未过期，直接返回店铺信息
            return r;
        }
        //5.2 已过期，需要缓存重建
        //6 缓存重建
        //6.1 获取互斥锁
        String lockKey = lockKeyPrefix + id;
        //6.2 判断是否获取互斥锁成功
        if (tryLock(lockKey)) {
            // 6.3 成功，开启独立线程，实现缓存重建
            EXECUTOR_SERVICE.submit(() -> {
                try {
                    R r1 = dbFallback.apply(id);
                    //写入redis
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        return r;
    }


    /**
     * 缓存击穿解决方案，互斥锁
     *
     * @param id
     * @return
     */
    private <R,ID> R queryWithMutex(String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallback,
                                    Long time, TimeUnit unit,String lockKeyPrefix) {
        R r;
        String key = keyPrefix + id;
        //1.从redis中查询数据库
        String json = this.get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在直接返回
            return JSONUtil.toBean(json, type);
        }
        //判断是否命中空值
        if (json != null) {
            return null;
        }
        //4实现缓存重建
        //4.1 获取互斥锁
        String lockKey = lockKeyPrefix + id;
        try {
            boolean isLock = tryLock(lockKey);
            if (!isLock) {
                //4.3 失败，休眠并重试
                Thread.sleep(50);
                queryWithMutex(keyPrefix,id,type,dbFallback,time,unit,lockKeyPrefix);
            }
            //4.2 判断是否获取成功
            //获取锁后，再次检查是否被之前的线程重建过了，双重检锁
            String json2 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(json2)) {
                return JSONUtil.toBean(json2, type);
            }
            //4.4 成功 查询数据库
            r = dbFallback.apply(id);
            //查询库是空的，返回空数据
            if (ObjectUtil.isEmpty(r)) {
                this.set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //库里存在，redis缓存
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r),
                    time, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        //返回信息
        return r;
    }

}
